import axios from "axios";
import qs from "qs";
import VueCookies from "vue-cookies";
import Router from "@/router";

const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API,
	// baseURL: "https://ykshuju.com/api",
	withCredentials: false,
	timeout: 15000,
});

// 请求拦截器
service.interceptors.request.use(
	(config) => {
		if (VueCookies.get("_token_finance")) {
			VueCookies.set("_token_finance", VueCookies.get("_token_finance"), 60 * 60 * 24 * 30);
			VueCookies.set("_user_finance", VueCookies.get("_user_finance"), 60 * 60 * 24 * 30);
			config.headers["token"] = VueCookies.get("_token_finance");
		}
		if (Object.getOwnPropertyNames(config.data ? config.data : {}).length !== 0) {
			config.data = qs.stringify(config.data);
		}
		// get请求映射params参数
		if (config.method === "get" && config.params) {
			let url = config.url + "?";
			for (const propName of Object.keys(config.params)) {
				const value = config.params[propName];
				var part = encodeURIComponent(propName) + "=";
				if (value && typeof value !== "undefined") {
					if (typeof value === "object") {
						for (const key of Object.keys(value)) {
							let params = propName + "[" + key + "]";
							var subPart = encodeURIComponent(params) + "=";
							url += subPart + encodeURIComponent(value[key]) + "&";
						}
					} else {
						url += part + encodeURIComponent(value) + "&";
					}
				}
			}
			url = url.slice(0, -1);
			config.params = {};
			config.url = url;
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response) => {
		// console.log('response', response);
		// 如果后台通过header返回token，说明token已经更新，则更新客户端本地token
		// if (response.headers.token) {
		//     store.dispatch('toggleToken', response.headers.token);
		// }
		const res = response.data;
		return res;
	},
	(error) => {
		if (error == "Error: Request failed with status code 401") {
			VueCookies.remove("_token_");
			VueCookies.remove("_user_");
			Router.replace(`/login`);
		}
		console.log(error);
	}
);

export default service;
